package kz.kstu.scantest.desktop.api;

import kz.kstu.scantest.business.entity.data.AnswerData;
import kz.kstu.scantest.business.entity.data.FormData;
import kz.kstu.scantest.business.entity.data.SubjectData;
import kz.kstu.scantest.business.entity.data.SubjectEnum;
import kz.kstu.scantest.business.util.StringUtil;

import javax.swing.table.AbstractTableModel;
import java.util.Collection;
import java.util.List;

/**
 * @author Filipp_Stankevich
 *         created: 17.09.11 16:09
 */
public class FormDataTableModel extends AbstractTableModel {

    public static final String SUBJECT_COLUMN_NAME = "Предмет";
    private static final int COLUMN_COUNT = 26;
    private FormData formData;

    public FormDataTableModel(FormData formData) {
        this.formData = formData;
    }

    @Override
    public int getRowCount() {
        return formData.getSubjects().size();
    }

    @Override
    public int getColumnCount() {
        return COLUMN_COUNT;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        SubjectData subjectData = getSubjectDataByRowIndex(rowIndex);
        if (columnIndex == 0) {
            SubjectEnum subject = subjectData.getSubjectEnum();
            return subject != null ? subject.getSubjectName() : StringUtil.EMPTY_STRING;
        } else {
            List<AnswerData> answerDataList = subjectData.getAnswers();
            AnswerData answerData = answerDataList.get(columnIndex - 1);
            return answerData.getValue();
        }
    }

    @Override
    public String getColumnName(int columnIndex) {
        if (columnIndex == 0) {
            return SUBJECT_COLUMN_NAME;
        } else {
            return String.valueOf(columnIndex);
        }
    }

    private SubjectData getSubjectDataByRowIndex(int rowIndex) {
        Collection<SubjectData> subjects = formData.getSubjects().values();
        SubjectData[] subjectDataArray = subjects.toArray(new SubjectData[subjects.size()]);
        return subjectDataArray[rowIndex];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return !(columnIndex == 0 && rowIndex <= 3);
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        SubjectData subjectData = getSubjectDataByRowIndex(rowIndex);
        if (columnIndex == 0) {
            subjectData.setSubjectEnum((SubjectEnum) aValue);
        } else {
            List<AnswerData> answerDataList = subjectData.getAnswers();
            AnswerData answerData = answerDataList.get(columnIndex - 1);
            answerData.setValue((String) aValue);
        }
    }
}
